package com.csxy.news.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.csxy.news.bean.News;
import com.csxy.news.util.JdbcUtil;
import com.csxy.news.util.StringUtil;

/**
 * 新闻数据访问类：数据访问层
 * @author Administrator
 *
 */
public class NewsDao {

	//获取新闻记录的总数
	public long findTotal() {
		try {
			JdbcUtil.openConnection();
			return JdbcUtil.countOf("id", "news");
		} catch (Exception e) {
            System.out.println(e.getMessage()); 
		} finally {
			JdbcUtil.closeConnection();
		}
		return 0;
	}

	//根据指定的条件，查询所有新闻记录列表
	public List<News> findAll(String whereClase,Object...params) {
		List<News> newsList=new ArrayList<News>();
		try {
			JdbcUtil.openConnection();
			List<Map<String,Object>> rowList=JdbcUtil.selectAll("select * from `news` where "+whereClase, params);
			for (Map<String, Object> row : rowList) {
				News news=JdbcUtil.mapToBean(News.class, row);
				newsList.add(news);
			}
		} catch (Exception e) {

		} finally {
			JdbcUtil.closeConnection();
		}
		return newsList;
	}

	/**
	 * 根据指定的分页条件进行查询
	 * @param offset
	 * @param count
	 * @param whereClase 形如"id=? and name like ?"
	 * @param params
	 * @return
	 */
	public List<News> findPagerAll(long offset,int count, String whereClase, Object... params) {
		
		List<News> newsList=new ArrayList<News>();
		StringBuffer sb=new StringBuffer();
		sb.append("select * from `news` ");
		if(!StringUtil.isEmpty(whereClase)){
			sb.append(" where ").append(whereClase);
		}
		sb.append(" limit ").append(offset).append(",").append(count);
		
		try {
			JdbcUtil.openConnection();
			List<Map<String,Object>> rowList=JdbcUtil.selectAll(sb.toString(), params);
			for (Map<String, Object> row : rowList) {
				News news=JdbcUtil.mapToBean(News.class, row);
				newsList.add(news);
			}
		} catch (Exception e) {

		} finally {
			JdbcUtil.closeConnection();
		}
		
		return newsList;
	}

	
}
